﻿package net.wangit.view.enumeration;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.framework.config.DomainsSettings;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.ServerAccessException;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.util.Checker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class EnumerationConfigFactory {

	private static final Log log = LogFactory
			.getLog(net.wangit.view.enumeration.EnumerationConfigFactory.class);
	private static final String SQL_CONFIG = "select * from ENUMCONFIG where enumid=? ";
	private static final String SQL_ITEM = "select name,value,custom,id from ENUM where enumid=? and v=1 order by id";

	public EnumerationConfigFactory() {
	}

	public static EnumerationConfig getEnumerationConfig(String domain,
			String eid) {
		EnumerationConfig config = EnumerationConfigCache.get(domain, eid);
		if (config == null) {
			config = Create(domain, eid);
			EnumerationConfigCache.put(domain, eid, config);
		}
		return config;
	}

	private static EnumerationConfig Create(String domain, String eid) {
		DB db = DBHelper.getDomainDB(domain);
		MapList list;
		try {
			list = db.query(EnumerationConfigFactory.SQL_CONFIG, eid, 2);
		} catch (Exception e) {
			log.error((new StringBuilder(
					"could not query enumeration in server: ")).append(domain)
					.toString(), e);
			throw new ServerAccessException((new StringBuilder(
					"could not query enumeration in server: ")).append(domain)
					.toString());
		}
		if (Checker.isEmpty(list)) {
			log.error((new StringBuilder("enumeration not found: ")).append(
					domain).append("/").append(eid).toString());
			throw new EnumerationConfigurationException((new StringBuilder(
					"enumeration not found: ")).append(domain).append("/")
					.append(eid).toString());
		}
		Row row = list.getRow(0);
		EnumerationConfig config = new EnumerationConfig(domain, eid);
		int dataMode = row.getInt("dm", 1);
		config.setDataMode(dataMode);
		String datasource = row.get("d");
		if (Checker.isEmpty(datasource))
			datasource = DomainsSettings.getDatasource(domain);
		config.setDatasource(datasource);
		config.setDataExpression(row.get("de"));
		config.setHasDataPrivilege(!Checker.isEmpty(row.get("dpid")));
		config.setCacheEnabled(!"0".equals(row.get("c")));
		config.setList(getItems(db, eid));
		return config;
	}

	private static MapList getItems(DB db, String eid) {
		try {
			return db.query(EnumerationConfigFactory.SQL_ITEM, eid, 2);
		} catch (Exception e) {
			return null;
		}
	}

}
